import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
// import { getOnlineLogsList } from "@/apiOld/system";
import { reactive, ref, onMounted, watch, nextTick, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import {
  callReport_calendarByMonth,
  callReport_wholeByDay,
  callReport_tasksByDay,
  callReport_staffsByDay,
  callReport_periodsByDay
} from "@/api/outbound";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_callCount_calendar: false, // 日历

    is_search_name: false, // 搜索名称
    is_search_status: false, // 搜索状态

    is_single_watch: false, // 监控
    is_single_recycle: false, // 回收未接
    is_single_pause: false, // 暂停
    is_single_excute: false, // 开始
    is_single_delete: false, // 删除

    is_batch_delete: false, // 批量删除
    is_batch_recycle: false, // 批量回收未接
  })

  /** TAB相关 */
  const tabList = ref([]);
  const tab = ref();
  function changeRadio(val){
    tab.value = val
    calendarDate.value = dayjs().toDate()
    if(val == "群呼指征"){
      getCheckedDayData(dayjs().format("YYYY-MM-DD"));
    }else if(val == "任务指征"){
      onTaskSearch(dayjs().format("YYYY-MM-DD"))
    }else if(val == "成员指征"){
      onUserSearch(dayjs().format("YYYY-MM-DD"))
    }else{
      onTimeSearch(dayjs().format("YYYY-MM-DD"))
    }
  }
  /** 日历相关 */
  const selectedMonth = ref(dayjs().format("YYYY-MM"));
  const calendarDate = ref(dayjs().toDate());

  // 获取月份通话日历
  const callMonth = ref(); // 当天是否拨打外呼
  function getMonth(Month) {
    callReport_calendarByMonth({
      month: Month
    }).then(res => {
      if (res.code == 1000) {
        callMonth.value = res.data;
      }
    });
  }

  const handleMonthChange = val => {
    if (val) {
      const originalDate = dayjs(calendarDate.value);
      const date = dayjs(val).set("date", originalDate.date());
      calendarDate.value = date.toDate();
      getMonth(val);
      if( tab.value == "群呼指征" ){
        getCheckedDayData(date.format("YYYY-MM-DD"));
      }else if( tab.value == "任务指征"){
        onTaskSearch(date.format("YYYY-MM-DD"))
      }else if( tab.value == "成员指征" ){
        onUserSearch(date.format("YYYY-MM-DD"))
      }else {
        onTimeSearch(date.format("YYYY-MM-DD"))
      }

    }
  };

  function isHoliday(date: string) {
    const day = dayjs(date).format("DD");

    const isTrue = callMonth.value?.[day];

    return isTrue == 1;
  }
  // 获取当天整体群呼特征
  const callData = ref({}); // 群呼指证数据
  function getCheckedDayData(day: string = dayjs().format("YYYY-MM-DD")) {
    callReport_wholeByDay({
      day
    }).then(res => {
      if (res.code == 1000) {
        callData.value = res.data;
      }
    });
  }

  /** 任务指征 列表相关 */
  const taskDataList = ref([]);
  const taskLoading = ref(true);
  const taskColumns: TableColumnList = [
    {
      label: "任务名称",
      prop: "taskName",
      fixed: "left"
    },
    {
      label: "消费金额",
      prop: "cost"
    },
    {
      label: "呼叫总数",
      prop: "callAll"
    },
    {
      label: "应答数",
      prop: "answer"
    },
    {
      label: "应答率",
      prop: "answerRate"
    },
    {
      label: "成功数",
      prop: "success"
    },
    {
      label: "成功率",
      prop: "successRate"
    },
    {
      label: "转接数",
      prop: "transfer"
    },
    {
      label: "转接率",
      prop: "transferRate"
    },
    {
      label: "呼损数",
      prop: "lose"
    },
    {
      label: "呼损率",
      prop: "loseRate"
    }
  ];

  async function onTaskSearch(day: string = dayjs().format("YYYY-MM-DD")) {
    taskLoading.value = true;
    callReport_tasksByDay({ day }).then(res=>{
      if(res.code == 1000){
        taskDataList.value = res.data
        taskLoading.value = false;
      }
    });
  }

  /** 成员指征 列表相关 */
  const userDataList = ref([]);
  const userLoading = ref(true);
  const userColumns: TableColumnList = [
    {
      label: "姓名",
      prop: "nickname",
      fixed: "left",
      width: 120
    },
    {
      label: "消费金额",
      prop: "cost"
    },
    // {
    //   label: "签入时长",
    //   prop: "time"
    // },
    {
      label: "呼叫总数",
      prop: "callAll"
    },
    {
      label: "呼入数",
      prop: "callinCnt"
    },
    {
      label: "呼出数",
      prop: "calloutCnt"
    },
    {
      label: "应答数",
      prop: "answer"
    },
    {
      label: "应答率",
      prop: "answerRate"
    },
    {
      label: "成功数",
      prop: "success"
    },
    {
      label: "成功率",
      prop: "successRate"
    },
    {
      label: "平均通话时长（秒）",
      prop: "talkTimeAverage",
      width: 150
    },
    {
      label: "通话总时长（秒）",
      prop: "talkTimeAll",
      width: 140
    }
  ];

  async function onUserSearch(day: string = dayjs().format("YYYY-MM-DD")) {
    userLoading.value = true;
    callReport_staffsByDay({ day }).then(res=>{
      if(res.code == 1000){
        userLoading.value = false;
        userDataList.value = res.data
      }
    })
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    // onTaskSearch();
    // onUserSearch();
  }

  /** 时段指征 列表相关 */
  const timeDataList = ref([]);
  const timeLoading = ref(true);
  const timeColumns: TableColumnList = [
    {
      label: "时段",
      prop: "hour",
      fixed: "left",
      width: 120,
      formatter: ({hour}) =>{
        if(hour<24){
          return `${hour}:00-${hour+1}:00`
        }else{
          return `${hour}:00-1:00`
        }
      }
    },
    {
      label: "消费金额",
      prop: "cost"
    },
    {
      label: "呼叫总数",
      prop: "callAll"
    },
    {
      label: "应答数",
      prop: "answer"
    },
    {
      label: "应答率",
      prop: "answerRate"
    },
    {
      label: "成功数",
      prop: "success"
    },
    {
      label: "成功率",
      prop: "successRate"
    },
    {
      label: "转接数",
      prop: "transfer"
    },
    {
      label: "转接率",
      prop: "transferRate"
    },
    {
      label: "呼损数",
      prop: "lose"
    },
    {
      label: "呼损率",
      prop: "loseRate"
    }
  ];

  async function onTimeSearch(day: string = dayjs().format("YYYY-MM-DD")) {
    timeLoading.value = true;
    callReport_periodsByDay({ day }).then(res=>{
      if(res.code == 1000){
        timeDataList.value = res.data
        timeLoading.value = false;
      }
    });
  }

  onMounted(() => {
    // onUserSearch();
    getMonth(selectedMonth.value);
    getCheckedDayData(dayjs().format("YYYY-MM-DD"));

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/groupcallManagement/reportForms/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/groupcallManagement/reportForms/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // callCount_calendar
      if (homeDataObj.callCount_calendar) permissions.is_callCount_calendar = true
      // callCount_tab
      if (homeDataObj.callCount_tab) {
        let childs = homeDataObj.callCount_tab.childs || []
        let filterTableList = []
        for (let i = 0; i < childs.length; i++) {
          let item = { label: "", value: childs[i] }
          if (childs[i] == 'whole') item.label = "群呼指征"
          if (childs[i] == 'task') item.label = "任务指征"
          if (childs[i] == 'member') item.label = "成员指征"
          if (childs[i] == 'period') item.label = "时段指征"
          filterTableList.push(item)
        }
        if (filterTableList.length) {
          tabList.value = filterTableList;
          tab.value = filterTableList[0].label;
        }
      }
    }
  });

  return {
    permissions,

    dayjs,
    tabList,
    tab,
    getMonth,

    selectedMonth,
    calendarDate,

    taskLoading,
    taskColumns,
    taskDataList,

    userLoading,
    userColumns,
    userDataList,
    timeDataList,
    timeColumns,
    timeLoading,
    callData,
    getCheckedDayData,
    onTimeSearch,

    handleMonthChange,
    isHoliday,

    onTaskSearch,

    onUserSearch,

    deviceDetection,

    handleOffline,
    changeRadio
  };
}
